package com.simu.towercrane.fragments;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.FindCallback;
import com.baidu.navi.activity.RouteGuideDemo;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.simu.towercrane.R;

public class ProductSurveyFragment extends BaseFragmentTwo {
	View view = null;
	private Context mContext;
	AVQuery<AVObject> query;
	int currentWhere;
	private ArrayList<String> listImage = new ArrayList<String>();
	private List<Map<String, Object>> mList;
	private double latitude = 0.0;
	private double longitude = 0.0;
	private ImageLoader mImageLoader;
	private static final double EARTH_RADIUS = 6378137;
	private ImageView IVproductImage;
	private ImageView IVproductAuthentication;
	private TextView TVproductDetils;
	private TextView TVproductPrice;
	private TextView TVproductTime;
	private TextView TVcompanyName;
	private TextView TVcompanyAuthentication;
	private TextView TVcompanyDistance;
	private TextView TVcompanyAddress;
	private TextView TVproductDistance;
	private TextView TVproductAddress;
	private TextView TVproductContent;
	private TextView TVproductName;
	private String addr;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mImageLoader = ImageLoader.getInstance();
		mContext = getActivity().getApplicationContext();
		if (view == null) {
			Log.d("fragmentLife", "FragmentTwoonCreateView");
			view = inflater.inflate(R.layout.fragment_product_survey, null);
		}
		Tool.destroyParent(view);
		Intent intent = getActivity().getIntent();
		String objectID = intent.getStringExtra("objectID");
		SharedPreferences SP = getActivity().getSharedPreferences("user", 0);
		latitude = Double.valueOf(SP.getString("latitude", "0")).doubleValue();
		longitude = Double.valueOf(SP.getString("lontitude", "0"))
				.doubleValue();
		addr = SP.getString("addr", "");
		addproduct(objectID);

		return view;
	}

	public void addproduct(String objectID) {

		query = new AVQuery<AVObject>("Commodity");
		query.whereEqualTo("objectId", objectID);
		query.include("vendor");
		query.findInBackground(new FindCallback<AVObject>() {

			@Override
			public void done(List<AVObject> list, AVException arg1) {
				// TODO Auto-generated method stub
				mList = new ArrayList<Map<String, Object>>();
				mList.clear();
				if (list != null) {

					for (int i = 0; i < list.size(); i++) {
						currentWhere = list.size();
						final HashMap<String, Object> map = new HashMap();
						map.clear();

						AVObject parent = list.get(i);
						// parent.getString("name");

						AVRelation<AVObject> avRelation = parent
								.getRelation("image");
						AVQuery<AVObject> avQuery = avRelation.getQuery();
						avQuery.findInBackground(new FindCallback<AVObject>() {

							@Override
							public void done(List<AVObject> arg0,
									AVException arg1) {
								if (arg0 != null) {

									// listImage.clear();

									for (int k = 0; k < arg0.size(); k++) {
										AVObject avobject = arg0.get(k);
										AVFile avFile = avobject
												.getAVFile("image");
										String url = avFile.getUrl();
										listImage.add(url);
										if (k == 0) {
											map.put("url", url);
										}
									}

									map.put("urls", listImage);
									initView(map);

								}

							}
						});

						AVRelation<AVObject> avRelationparams = parent
								.getRelation("params");
						AVQuery<AVObject> avQueryparams = avRelationparams
								.getQuery();
						avQueryparams
								.findInBackground(new FindCallback<AVObject>() {

									@Override
									public void done(List<AVObject> arg0,
											AVException arg1) {
										String content = null;
										String name = null;
										if (arg0 != null) {
											for (int k = 0; k < arg0.size(); k++) {

												if (k == 0) {
													content = arg0.get(k)
															.getString("name")
															+ ":\t\t"
															+ arg0.get(k)
																	.getString(
																			"content");
												} else if (k == 1) {
													name = arg0.get(k)
															.getString("name")
															+ ":\t\t"
															+ arg0.get(k)
																	.getString(
																			"content");
												} else if (k % 2 == 0) {

													content = arg0.get(k)
															.getString("name")
															+ ":\t\t"
															+ arg0.get(k)
																	.getString(
																			"content")
															+ "\n" + content;
												} else {
													name = arg0.get(k)
															.getString("name")
															+ ":\t\t"
															+ arg0.get(k)
																	.getString(
																			"content")
															+ "\n" + name;
												}

											}
											map.put("content", content);
											map.put("name", name);
											initView(map);
										}

									}
								});

						List<AVObject> listpint = new ArrayList<AVObject>();
						listpint.add(list.get(i).getAVObject("vendor"));

						map.put("vendorAddress", listpint.get(0).get("address"));
						Object Tag = listpint.get(0).get("tag");

						@SuppressWarnings("unchecked")
						ArrayList<String> tag = (ArrayList) Tag;
						if (tag != null) {

							map.put("vendorAuthentication", "certified");
						} else {
							map.put("vendorAuthentication", "NOTcertified");
						}

						List<AVObject> listproductcertifiedInfo = new ArrayList<AVObject>();
						listproductcertifiedInfo.add(list.get(i).getAVObject(
								"certifiedInfo"));
						if (listproductcertifiedInfo.toString()
								.equals("[null]")) {
							map.put("iscertifiedInfo", "NOTcertifiedInfo");

						} else
							map.put("iscertifiedInfo", "certifiedInfo");

						map.put("vendorName", listpint.get(0).get("vendorName"));
						double latitudevendor = listpint.get(0)
								.getAVGeoPoint("location").getLatitude();
						double longitudevendor = listpint.get(0)
								.getAVGeoPoint("location").getLongitude();
						double vendorDistance = DistanceOfTwoPoints(latitude,
								longitude, latitudevendor, longitudevendor);
						int vendordistance = (int) vendorDistance;
						if (vendorDistance < 1000) {
							map.put("vendorlocation", vendordistance + "M");
						} else {
							map.put("vendorlocation", vendordistance / 1000
									+ "KM");
						}
						map.put("name", list.get(i).getString("name"));

						map.put("summary", list.get(i).getString("summary"));
						map.put("price", list.get(i).getInt("price") + "");
						map.put("objectID", list.get(i).getObjectId());

						double latitudeproduct = list.get(i)
								.getAVGeoPoint("location").getLatitude();
						double longitudeproduct = list.get(i)
								.getAVGeoPoint("location").getLongitude();
						double Distance = DistanceOfTwoPoints(latitude,
								longitude, latitudeproduct, longitudeproduct);
						int distance = (int) Distance;
						if (Distance < 1000) {
							map.put("location", distance + "M");
						} else {
							map.put("location", distance / 1000 + "KM");
						}

						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss ");
						String textday = sdf.format(list.get(i).getDate(
								"expiryDate"));
						map.put("effectiveDate", textday);
						map.put("latitude", latitude);
						map.put("longitude", longitude);
						map.put("addr", addr);
						map.put("address", list.get(i).getString("address"));
						map.put("latitudeproduct", latitudevendor);
						map.put("longitudeproduct", longitudeproduct);
						map.put("latitudevendor", latitudevendor);
						map.put("longitudevendor", longitudevendor);

					}

				}

			}
		});

	}

	@SuppressLint("ResourceAsColor")
	public void initView(final HashMap<String, Object> map) {
		IVproductImage = (ImageView) view.findViewById(R.id.iv_product_image);
		IVproductAuthentication = (ImageView) view
				.findViewById(R.id.iv_simuAuthentication);
		TVproductDetils = (TextView) view.findViewById(R.id.tv_product_detail);
		TVproductPrice = (TextView) view.findViewById(R.id.tv_product_price);
		TVproductTime = (TextView) view.findViewById(R.id.tv_product_time);
		TVcompanyName = (TextView) view
				.findViewById(R.id.tv_product_companyname);
		TVcompanyAuthentication = (TextView) view
				.findViewById(R.id.tv_product_companynAuthentication);
		TVcompanyDistance = (TextView) view
				.findViewById(R.id.tv_company_distance);
		TVcompanyAddress = (TextView) view
				.findViewById(R.id.tv_product_companyadress);
		TVproductAddress = (TextView) view
				.findViewById(R.id.tv_product_productaddress);
		TVproductContent = (TextView) view
				.findViewById(R.id.tv_product_content);
		TVproductName = (TextView) view.findViewById(R.id.tv_product_name);
		TVproductDistance = (TextView) view
				.findViewById(R.id.tv_product_productdistance);
		String url = map.get("url") + "";
		mImageLoader.displayImage(url, IVproductImage);
		// IVproductAuthentication=(ImageView)view.findViewById(R.id.iv_simuAuthentication);
		TVproductDetils.setText("" + map.get("summary"));
		TVproductPrice.setText("价格：" + "￥" + map.get("price"));
		TVproductTime.setText("" + map.get("effectiveDate"));
		// TVcompanyName.
		// TVcompanyAuthentication=(TextView)view.findViewById(R.id.tv_product_companynAuthentication);
		// TVcompanyDistance=(TextView)view.findViewById(R.id.tv_product_productdistance);
		// TVcompanyAddress=(TextView)view.findViewById(R.id.tv_product_companyadress);
		TVcompanyName.setText("" + map.get("vendorName"));
		TVproductDistance.setText("" + map.get("location"));

		TVcompanyDistance.setText("" + map.get("vendorlocation"));
		TVcompanyAddress.setText("" + map.get("vendorAddress"));

		if (map.get("iscertifiedInfo").equals("NOTcertifiedInfo")) {
			IVproductAuthentication.setVisibility(View.INVISIBLE);

		}

		if (map.get("vendorAuthentication").equals("certified")) {
			TVcompanyAuthentication.setVisibility(View.VISIBLE);
			TVcompanyAuthentication.setText("认证商家");
			TVcompanyAuthentication.setTextColor(R.color.top_bar_normal_bg);
		} else {
			TVcompanyAuthentication.setVisibility(View.INVISIBLE);
		}
		// TVcompanyAuthentication.setText("认证商家");

		TVproductAddress.setText("" + map.get("address"));
		TVproductContent.setText("" + map.get("content"));
		TVproductName.setText("" + map.get("name"));
		TVproductDistance.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				Intent intent = new Intent();
				intent.setClass(getActivity(), RouteGuideDemo.class);
				intent.putExtra("startlatitude", map.get("latitude") + "");
				intent.putExtra("startlongitude", map.get("longitude") + "");
				intent.putExtra("endlatitude", map.get("latitudeproduct") + "");
				intent.putExtra("endlongitude", map.get("longitudeproduct")
						+ "");
				intent.putExtra("startName", map.get("addr") + "");
				intent.putExtra("endNamge", map.get("address") + "");
				// intent.putExtra("objectID", getId());
				getActivity().startActivity(intent);

			}
		});
		TVcompanyDistance.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(getActivity(), RouteGuideDemo.class);
				intent.putExtra("startlatitude", map.get("latitude") + "");
				intent.putExtra("startlongitude", map.get("longitude") + "");
				intent.putExtra("endlatitude", map.get("latitudevendor") + "");
				intent.putExtra("endlongitude", map.get("longitudevendor") + "");
				intent.putExtra("startName", map.get("addr") + "");
				intent.putExtra("endNamge", map.get("vendorAddress") + "");
				// intent.putExtra("objectID", getId());
				getActivity().startActivity(intent);
			}
		});
	}

	public void getlocation() {
		LocationManager locationManager = (LocationManager) getActivity()
				.getSystemService(Context.LOCATION_SERVICE);
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Location location = locationManager
					.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if (location != null) {
				latitude = location.getLatitude();
				longitude = location.getLongitude();
			} else {
				LocationListener locationListener = new LocationListener() {

					// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
					@Override
					public void onStatusChanged(String provider, int status,
							Bundle extras) {

					}

					// Provider被enable时触发此函数，比如GPS被打开
					@Override
					public void onProviderEnabled(String provider) {

					}

					// Provider被disable时触发此函数，比如GPS被关闭
					@Override
					public void onProviderDisabled(String provider) {

					}

					// 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
					@Override
					public void onLocationChanged(Location location) {
						if (location != null) {
							Log.e("Map",
									"Location changed : Lat: "
											+ location.getLatitude() + " Lng: "
											+ location.getLongitude());
							latitude = location.getLatitude(); // 经度
							longitude = location.getLongitude(); // 纬度
						}
					}
				};
				locationManager.requestLocationUpdates(
						LocationManager.NETWORK_PROVIDER, 1000, 0,
						locationListener);
				Location location1 = locationManager
						.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				if (location1 != null) {
					latitude = location1.getLatitude(); // 经度
					longitude = location1.getLongitude(); // 纬度
				}
			}
		}
	}

	public static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	public static double DistanceOfTwoPoints(double lat1, double lng1,
			double lat2, double lng2) {
		double radLat1 = rad(lat1);
		double radLat2 = rad(lat2);
		double a = radLat1 - radLat2;
		double b = rad(lng1) - rad(lng2);
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}
}
